package service

import (
	"context"
	"gitee.com/crack007/timingwheel"
	"github.com/crack007/fpm_metrics/src/config"
	"github.com/crack007/fpm_metrics/src/constant"
	"github.com/crack007/fpm_metrics/src/counter"
	"time"
)

type ScheduleService struct {
}

// work 定时任务
func (s *ScheduleService) work() {
	fpmStatusModel := GetFpmService().Stat()
	counter.GetCounter(constant.ACCEPTED_CONN).Set(float64(fpmStatusModel.AcceptedConn))
	counter.GetCounter(constant.ACTIVE_PROCESSES).Set(float64(fpmStatusModel.ActiveProcesses))
	counter.GetCounter(constant.MAX_ACTIVE_PROCESSES).Set(float64(fpmStatusModel.MaxActiveProcesses))
	counter.GetCounter(constant.IDLE_PROCESSES).Set(float64(fpmStatusModel.IdleProcesses))
	counter.GetCounter(constant.TOTAL_PROCESSES).Set(float64(fpmStatusModel.TotalProcesses))
	counter.GetCounter(constant.START_SINCE).Set(float64(fpmStatusModel.StartSince))
	counter.GetCounter(constant.LISTEN_QUEUE).Set(float64(fpmStatusModel.ListenQueue))
	counter.GetCounter(constant.LISTEN_QUEUE_LEN).Set(float64(fpmStatusModel.ListenQueueLen))
	counter.GetCounter(constant.MAX_CHILDREN_REACHED).Set(float64(fpmStatusModel.MaxChildrenReached))
	counter.GetCounter(constant.SLOW_REQUESTS).Set(float64(fpmStatusModel.SlowRequests))
}

func (s *ScheduleService) Bootstrap(ctx context.Context) {
	// 创建schedule对象
	schedule := timingwheel.NewDefaultSchedule(ctx)

	// 延迟时间(单位：毫秒)
	delayTime := time.Duration(config.GetInterval()) * time.Second
	task := timingwheel.NewTask(delayTime, func(task *timingwheel.Task) {
		// 触发回调逻辑
		s.work()
		schedule.PushTask(task)
	})
	schedule.PushTask(task)

}
